package com.rs2lite.utils;

import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.util.Random;

/**
 * Class AutoTyper, allows the client to send variable text
 * 
 * Note: This class is currently in development, and will be changed to include
 * a delay.
 * 
 * @author Nicole <nicole@rune-server.org> This file is protected by The BSD
 *         License, You should have recieved a copy named "BSD License.txt"
 */

public class AutoTyper {

	private Robot robot;

	private Random random = new Random();

	private String[] textsToSay = new String[10];

	private boolean running = false;

	private long delay = 4000;

	private int index = 0;

	private boolean paused = false;

	public AutoTyper() {
		try {
			robot = new Robot();
		} catch (AWTException e) {
			e.printStackTrace();
		}
	}

	public class AutoTyperRunnable implements Runnable {
		@Override
		public void run() {
			while (running) {
				checkPause();
				if (index >= 10 || textsToSay.length == index
						|| textsToSay[index] == null) {
					index = 0;
				}
				String s = textsToSay[index++];
				for (char c : s.toCharArray()) {
					checkPause();
					if (Character.isSpaceChar(c)) {
						robot.keyPress(KeyEvent.VK_SPACE);
						robot.keyRelease(KeyEvent.VK_SPACE);
						continue;
					}

					if (Character.isUpperCase(c)) {
						robot.keyPress(KeyEvent.VK_SHIFT);
					}

					robot.keyPress(Character.toUpperCase(c));
					robot.keyRelease(Character.toUpperCase(c));

					if (Character.isUpperCase(c)) {
						robot.keyRelease(KeyEvent.VK_SHIFT);
					}
					try {
						Thread.sleep(random.nextInt(100));
					} catch (Exception e) {
						break;
					}
				}
				robot.keyPress(KeyEvent.VK_ENTER);
				robot.keyRelease(KeyEvent.VK_ENTER);
				try {
					Thread.sleep(delay + random.nextInt((int) delay / 3));
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}

		private void checkPause() {
			if (paused) {
				while (paused) {
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}

	public void start(String[] strings) {
		this.textsToSay = strings;
		running = true;
		new Thread(new AutoTyperRunnable()).start();
	}

	public void stop() {
		running = false;
	}

	public void pause(boolean b) {
		paused = b;
	}

	public boolean isRunning() {
		return running;
	}

	public boolean isPaused() {
		return paused;
	}

	public String[] getTexts() {
		return textsToSay;
	}

	public void setDelay(long l) {
		this.delay = l;
	}

	public long getDelay() {
		return delay;
	}
}
